<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
      }"
      :table-props="{
        selection: true,
        delBtn: true,
        viewBtn: true,
        editBtn: true,
        menuSlot: true,
        menuWidth: 300,
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #rightToolbar></template>
      <template #menuSlot></template>
      <template #type="scope:any">
        <DictTag :options="AdsTypeEnum" :value="scope.row.type" />
      </template>

      <template #status="scope:any">
        <el-switch v-model="scope.row.status" active-value="Enabled" inactive-value="Disabled" @change="handleStatusChange(scope.row)" />
      </template>
    </yt-crud>
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'

import {adsList, adsDelete, adsSave, adsBatchDelete, changeStatus } from '@/api/business/ads'
import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { AdsTypeEnum, EnableStatusEnum } = toRefs<any>(proxy?.useEnum('ads_type_enum', 'enable_status_enum'))
const { t } = useI18n()

const state = reactive({
  page: {
    pageSize: 12,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  showDeviceMap: true,
  mapLnglat: '' as any,
  query: {},
})

const column = ref<IColumn[]>([
  {
    label: t('business.ads.name'),
    key: 'name',
    type: 'i18nString',
    search: true,
    formHide: false,
    searchLabelWidth: 120,
    colSpan: 22,
    rules: [{ required: true, message: t('business.ads.validator.name') }],
  },
  {
    label: t('business.ads.type'),
    key: 'type',
    type: 'select',
    componentProps: {
      options: AdsTypeEnum,
    },
    search: true,
    formHide: false,
    slot: true,
    rules: [{ required: true, message: t('business.ads.validator.type') }],
    formWatch: (scope) => {
      scope.column.forEach((f: IColumn) => {
        if (f.key === 'content') {
          f.formHide = scope.value != 'Html'
        }
        if (f.key === 'link') {
          f.formHide = scope.value != 'OutLink'
        }
      })
      column.value = scope.column
    },
  },
  {
    label: t('business.ads.link'),
    key: 'link',
    hide: true,
    formHide: false,
    colSpan: 22,
    rules: [{ required: true, message: t('business.ads.validator.link') }],
  },
  {
    label: t('business.ads.content'),
    key: 'content',
    hide: true,
    type: 'i18nString',
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 5,
    },
    rules: [{ required: true, message: t('business.ads.validator.content') }],
  },
  {
    label: t('business.ads.img'),
    key: 'img',
    type: 'image',
    formHide: false,
    componentProps: {
      limit: 1,
      isShowTip: false,
      uploadType: 'url',
    },
    rules: [{ required: true, message: t('business.ads.validator.img') }],
  },
  {
    label: t('business.ads.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: true,
    slot: true,
  },

  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  adsList({
    ...state.page,
    ...state.query,
  })
    .then((res: any) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  adsSave(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

// 弹窗前置操作
const openBeforeFun = ({ type, data }) => {
  if (type === 'add') {
    state.mapLnglat = ''
  } else if (type === 'update') {
    const latitude = data?.locate?.latitude || ''
    const longitude = data?.locate?.longitude || ''
    state.mapLnglat = longitude + ',' + latitude
  }
}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    adsBatchDelete(row.map((m) => m.id))
      .then(() => {
        ElMessage.success(t('operate.tooltip.success'))
        getData()
      })
      .finally(() => {
        state.loading = false
      })
  } else {
    adsDelete(row.id)
      .then(() => {
        ElMessage.success(t('operate.tooltip.success'))
        getData()
      })
      .finally(() => {
      state.loading = false
    })
  }
}

const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>

<style lang="scss" scoped></style>
